<?php
namespace app\admin\controller;
use think\Db;
use think\Request;
use think\Log;
use think\Config;

class Shipping extends Base
{
	 /**
     * 待分配订单列表
     * @return [type] [description]
     */
    function index(){
    	$keywords = Request()->get('keywords');
        $create_time = Request()->get('create_time')?Request()->get('create_time'):"create_time desc";
        $this->assign('create_time',$create_time);
        // $Query = Db::field("*,max(create_time) as create_time")->name('order')->where("order_status=30");
        
        $Query = Db::field("o.*,max(o.create_time) as create_time")
            ->table('sdzx_order')->alias('o')
            ->join('sdzx_shipping s','o.order_id=s.order_id','left')

            ->where("order_status=30 and isnull(s.shipping_id)");

        if ($keywords) {
            $Query->where("user_name like '%{$keywords}%' or receiver_name like '%{$keywords}%' or receiver_mobile like '%{$keywords}%' or order_no like '%{$keywords}%'");
        }
        
        $list=$Query->order('create_time desc')->group('user_id')->select();

		foreach($list as $val){
			$group_list[] = Db::field('o.*')->table('sdzx_order')->alias('o')
            ->join('sdzx_shipping s','o.order_id=s.order_id','left')
            ->where(['o.user_id' => $val['user_id'],'o.order_status' => 30])
            ->where("isnull(s.shipping_id)")
            ->group('o.order_id')
            ->order('o.create_time desc')->select();
		}

		foreach($group_list as $val){
			foreach($val as $v){
				$orders_list[] = $v;
			}
		}
	
        $orders = [];
        foreach ($orders_list as $k => $v) {
            $orders[$v['order_id']]=$v;
        }

        //一口气查出商品
        $order_ids = array_column($orders,'order_id');

        $order_ids = $order_ids?:0;
        $goods = Db::field('g.*,ifnull(max(s.stock_num),0) as stock_num')->table('sdzx_order_goods')->alias('g')
        ->join('sdzx_stock s','g.goods_specval_id=s.specval_id','left')
        ->where(['order_id'=>['in',$order_ids]])
        ->group('g.order_id,g.goods_specval_id')
        ->select();
		
        foreach ($goods as $k => $v) {
            !isset($orders[$v['order_id']]['finish']) && $orders[$v['order_id']]['finish']=$v['num'] <= $v['stock_num']?true:false;
            $orders[$v['order_id']]['finish'] = ($orders[$v['order_id']]['finish'] && $v['num'] <= $v['stock_num']?true:false);
            $orders[$v['order_id']]['list'][] = $v;
        }

        // array_multisort(array_column($orders,'finish'), SORT_DESC, array_column($orders,'create_time'),SORT_ASC,$orders);
		
        $data['list'] = $orders;
        return $this->fetch('index',$data);
    }

    /**
     * 待分配订单列表
     * @return [type] [description]
     */
    function screen(){
        $keywords = Request()->get('keywords');

        $Query = Db::name('order')->where("order_status=30");
        if ($keywords) {
            $Query->where("user_name like '%{$keywords}%' or receiver_name like '%{$keywords}%' or receiver_mobile like '%{$keywords}%' or order_no like '%{$keywords}%'");
        }
        
        $list=$Query->select();
        $orders = [];
        foreach ($list as $k => $v) {
            $orders[$v['order_id']]=$v;
        }

        //一口气查出商品
        $order_ids = array_column($orders,'order_id');
        $order_ids = $order_ids?:0;
        $goods = Db::field('g.*,max(s.stock_num) as stock_num')->table('sdzx_order_goods')->alias('g')
        ->join('sdzx_stock s','g.goods_specval_id=s.specval_id','left')
        ->where(['order_id'=>['in',$order_ids]])
        ->group('g.order_id,g.goods_specval_id')
        ->select();

        foreach ($goods as $k => $v) {
            !isset($orders[$v['order_id']]['finish']) && $orders[$v['order_id']]['finish']=$v['num'] <= $v['stock_num']?true:false;
            $orders[$v['order_id']]['finish'] = ($orders[$v['order_id']]['finish'] && $v['num'] <= $v['stock_num']?true:false);

            $orders[$v['order_id']]['totalnum'] += $v['num'];
            $orders[$v['order_id']]['totalstocknum'] += $v['stock_num'];
            if ($orders[$v['order_id']]['totalstocknum']>$orders[$v['order_id']]['totalnum']) {
                $orders[$v['order_id']]['totalstocknum'] = $orders[$v['order_id']]['totalnum'];
            }
            $orders[$v['order_id']]['list'][] = $v;
        }
        array_multisort(array_column($orders,'finish'), SORT_DESC, $orders);
        $data['list'] = $orders;
        return $this->fetch('',$data);
    }

    /**
     * 分配
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function allot()
    {
    	if (Request()->isPost()) {
    		$param = Request()->param();
            
    		if (!isset($param['uid']) || empty($param['uid'])) {
    			$this->error('未选择配送员');
    		}

    		if (!isset($param['ids']) || empty($param['ids'])) {
    			$this->error('未选择订单');
    		}
    		//员工信息
    		$employee = DB::name('employee')->where(['id'=>['in',$param['uid']],'deleted'=>0,'status'=>1])->select();
    		if (!$employee) {
    			$this->error('配送员不存在或已禁用');
    		}

            $employeeId = array_column($employee,'id');
            $employeeName = array_column($employee,'name');

            //查出订单商品 
            $goods = Db::name('order_goods')->where(['order_id'=>['in',$param['ids']]])->select();

    		$time = date('Y-m-d H:i:s');

    		$orders = Db::name('order')->where(['order_id'=>['in',$param['ids']],'order_status'=>30])->select();
    		!$orders && $this->error('订单不存在');

            //看订单是否已经被分配
            $has = Db::field('shipping_id')->table('sdzx_order')->alias('o')
            ->join('sdzx_shipping s','o.order_id=s.order_id')
            ->where("o.order_id={$param['ids']}")
            ->find();

            $has && $this->error('订单已经被分配','refresh');

    		$Shipping = []; $orderAction = [];
    		foreach ($orders as $k => $v) {
    			$Shipping[] = [
					'order_id'      => $v['order_id'],
					'delivery_id'   => implode(',', $employeeId),
					'delivery_name' => implode(',',$employeeName),
					'shipping_create_time'   => $time,
					'shipping_create_id'     => $this->uid,
					'shipping_create_name'   => $this->user['name'],
					'shipping_status'        => 0,
    			];
                $orderAction[] = [
                    'user_id'          => $v['user_id'],
                    'order_id'         => $v['order_id'],
                    'act_time'         => date('Y-m-d H:i:s'),
                    'op_uid'           => $this->uid,
                    'op_uname'         => $this->user['name']?:$this->user['username'],
                    'order_status'     => 40,
                    'bop_order_status' => $v['order_status']
                ];
    		}
    		
    		// Db::startTrans();
    		$re_shipping = Db::name('shipping')->insertAll($Shipping);
            $shippingId  = Db::name('shipping')->getLastInsID();
    		if (!$re_shipping) {
    			Db::rollback(); $this->error('分配失败');
    		}

    		// 更改订单状态为配送中 40
    		$re_order = Db::name('order')->where(['order_id'=>['in',$param['ids']]])->update(['order_status'=>40,'shipping_time'=>$time]);
    		if ($re_order === false) {
    			Db::rollback(); $this->error('分配失败');
    		}

            //减库存
            foreach ($goods as $k => $v) {
                if (empty($v['num'])) {
                    continue;
                }
                $stock = Db::name('stock')->where(['specval_id'=>$v['goods_specval_id'],'stock_num'=>['egt',$v['num']]])->find();
                if (!$stock) {
                    Db::rollback(); $this->error('分配失败1');
                }

                $re_stock = Db::name('stock')->where(['stock_id'=>$stock['stock_id']])->setDec('stock_num',$v['num']);
                if (!$re_stock) {
                    Db::rollback(); $this->error('分配失败2');
                }
                //添加库存详情
                $re_stock_detail = Db::name('stock_detail')->insert([
                    'stock_id'     => $stock['stock_id'],
                    'depot_id'     => $stock['depot_id'],
                    'depot_name'   => $stock['depot_name'],
                    'goods_id'     => $v['goods_id'],
                    'specval_id'   => $v['goods_specval_id'],
                    'specval_name' => $v['goods_specval_name'],
                    'order_id'     => $v['order_id'],
                    'type'         =>  -1,
                    'num'          => $v['num'],
                    'price'        => $v['price'],
                    'time'         => $time,
                    'uid'          => $this->uid,
                    'uname'        => $this->user['name'],
                ]);
                if (!$re_stock_detail) {
                    Db::rollback(); $this->error('分配失败3');
                }
            }
            
            Db::name('order_action')->insertAll($orderAction);

    		Db::commit(); $this->success('分配成功','',['shippingId'=>$shippingId]);
    	}else{

            $param = Request()->param();
            if ($param['step']==2) {
                $employee_id = $param['uid'];
                $order_id = $param['order_id'];

                //订单商品
                $goods = Db::field('*')->name('order_goods')
                ->where(['order_id'=>$order_id])
                ->select();

                $data['list'] = $goods;
                $data['employee_id'] = $param['uid'];
                $data['order_id'] = $param['order_id'];

                return $this->fetch('outstock',$data);
            }else{
                $keywords = Request()->get('keywords');
                // 配送人员
                $Query = Db::field('e.id,e.nickname,e.name,e.phone,g.code,count(shipping_id) as num')
                ->table('sdzx_employee')->alias('e')
                ->join('sdzx_employee_group_relation r','e.id=r.uid')
                ->join('sdzx_employee_group g','r.group_id=g.id')
                ->join('sdzx_shipping s','find_in_set(e.id,s.delivery_id) != 0 and s.shipping_status=0','left')
                ->where("g.code='PS' and e.status=1 and e.deleted=0")
                ->group('e.id');

                if ($keywords) {
                    $Query->where("e.name like '%{$keywords}%' or e.phone like '%{$keywords}%'");
                }
                $list = $Query->select();
                $data['list'] = $list;
                $data['order_id'] = $param['order_id'];
                return $this->fetch('allot',$data);
            }
    		
    	}
    }

    public function outstock()
    {
        if (Request()->isPost()) {
            $param = Request()->param();
            //查出订单商品 
            $goods = Db::name('order_goods')->where(['order_id'=>['in',$param['ids']]])->select();

            $time = date('Y-m-d H:i:s');

            $orders = Db::name('order')->where(['order_id'=>['in',$param['ids']],'order_status'=>30])->select();
            !$orders && $this->error('订单不存在');
            $orderAction = [];
            foreach ($orders as $k => $v) {
                $orderAction[] = [
                    'user_id'          => $v['user_id'],
                    'order_id'         => $v['order_id'],
                    'act_time'         => date('Y-m-d H:i:s'),
                    'op_uid'           => $this->uid,
                    'op_uname'         => $this->user['name']?:$this->user['username'],
                    'order_status'     => 40,
                    'bop_order_status' => $v['order_status']
                ];
            }

            // 更改订单状态为配送中 40
            $re_order = Db::name('order')->where(['order_id'=>['in',$param['ids']]])->update(['order_status'=>40,'shipping_time'=>$time]);
            if ($re_order === false) {
                Db::rollback(); $this->error('出库失败');
            }

            //减库存
            foreach ($goods as $k => $v) {
                if (empty($v['num'])) {
                    continue;
                }
                $stock = Db::name('stock')->where(['specval_id'=>$v['goods_specval_id'],'stock_num'=>['egt',$v['num']]])->find();
                if (!$stock) {
                    Db::rollback(); $this->error('出库失败1');
                }

                $re_stock = Db::name('stock')->where(['stock_id'=>$stock['stock_id']])->setDec('stock_num',$v['num']);
                if (!$re_stock) {
                    Db::rollback(); $this->error('出库失败2');
                }
                //添加库存详情
                $re_stock_detail = Db::name('stock_detail')->insert([
                    'stock_id'     => $stock['stock_id'],
                    'depot_id'     => $stock['depot_id'],
                    'depot_name'   => $stock['depot_name'],
                    'goods_id'     => $v['goods_id'],
                    'specval_id'   => $v['goods_specval_id'],
                    'specval_name' => $v['goods_specval_name'],
                    'order_id'     => $v['order_id'],
                    'type'         =>  -1,
                    'num'          => $v['num'],
                    'price'        => $v['price'],
                    'time'         => $time,
                    'uid'          => $this->uid,
                    'uname'        => $this->user['name'],
                ]);
                if (!$re_stock_detail) {
                    Db::rollback(); $this->error('分配失败3');
                }
            }
            
            Db::name('order_action')->insertAll($orderAction);
            $this->sendTmp($orders[0]);
            $shippingId = Db::name('shipping')->where(['order_id'=>$param['ids']])->value('shipping_id');
            Db::commit(); $this->success('分配成功','',['shippingId'=>$shippingId]);
        }else{

            if ($param['step']==2) {
                $order_id = $param['order_id'];

                //订单商品
                $goods = Db::field('*')->name('order_goods')
                ->where(['order_id'=>$order_id])
                ->select();

                $data['list'] = $goods;
                $data['employee_id'] = $param['uid'];
                $data['order_id'] = $param['order_id'];

                return $this->fetch('outstock',$data);
            }else{

                $keywords = Request()->get('keywords');
                $create_time = Request()->get('create_time')?Request()->get('create_time'):"create_time desc";
                $this->assign('create_time',$create_time);
                $Query = Db::field("o.*,max(o.create_time) as create_time")
                ->table('sdzx_order')->alias('o')
                ->join('sdzx_shipping s','o.order_id=s.order_id')
                ->where("order_status=30");
                if ($keywords) {
                    $Query->where("user_name like '%{$keywords}%' or receiver_name like '%{$keywords}%' or receiver_mobile like '%{$keywords}%' or order_no like '%{$keywords}%'");
                }
                
                $list=$Query->order('create_time desc')->group('user_id')->select();

                foreach($list as $val){
                    $group_list[] = Db::field('o.*,s.shipping_id,s.delivery_name')->table('sdzx_order')->alias('o')
                    ->join('sdzx_shipping s','o.order_id=s.order_id')
                    ->where(['o.user_id' => $val['user_id'],'o.order_status' => 30])
                    ->group('o.order_id')
                    ->order('o.create_time desc')->select();
                }

                foreach($group_list as $val){
                    foreach($val as $v){
                        $orders_list[] = $v;
                    }
                }
            
                $orders = [];
                foreach ($orders_list as $k => $v) {
                    $orders[$v['order_id']]=$v;
                }

                //一口气查出商品
                $order_ids = array_column($orders,'order_id');

                $order_ids = $order_ids?:0;
                $goods = Db::field('g.*,ifnull(max(s.stock_num),0) as stock_num')->table('sdzx_order_goods')->alias('g')
                ->join('sdzx_stock s','g.goods_specval_id=s.specval_id','left')
                ->where(['order_id'=>['in',$order_ids]])
                ->group('g.order_id,g.goods_specval_id')
                ->select();
                
                foreach ($goods as $k => $v) {
                    !isset($orders[$v['order_id']]['finish']) && $orders[$v['order_id']]['finish']=$v['num'] <= $v['stock_num']?true:false;
                    $orders[$v['order_id']]['finish'] = ($orders[$v['order_id']]['finish'] && $v['num'] <= $v['stock_num']?true:false);
                    $orders[$v['order_id']]['list'][] = $v;
                }

                // array_multisort(array_column($orders,'finish'), SORT_DESC, array_column($orders,'create_time'),SORT_ASC,$orders);
                
                $data['list'] = $orders;
                return $this->fetch('noutstock',$data);
            }
        }
        
    }
    /**
     * 标题
    订单发货提醒
    关键词
    订单号
    {{keyword1.DATA}}
    商品名称
    {{keyword2.DATA}}
    发货时间
    {{keyword3.DATA}}
    收货地址
    {{keyword4.DATA}}
    姓名
    {{keyword5.DATA}}
    电话
    {{keyword6.DATA}}
    配送方式
    {{keyword7.DATA}}
     * @param  [type] $order [description]
     * @return [type]        [description]
     */
    function sendTmp($order){
        $goods = Db::field('goods_name')->name('order_goods')->where(['order_id'=>$order['order_id']])->limit(2)->select();
        $str_goods = implode(',',array_column($goods,'goods_name'));
        $str_goods .= '...';
        $prepay_id = Db::name('order_prepay')->where(['order_id'=>$order['order_id'],'status'=>1])->value('prepay_id');
        $d = [
            'touser'  => $order['openid'],
            'page'    => "pages/order_detail/order_detail?order_id={$order['order_id']}",
            'form_id' => $prepay_id,
            'data' => [
                'keyword1'=>$order['order_no'], //单号
                'keyword2'=>$str_goods, //下单时间
                'keyword3'=>date('Y-m-d H:i:s'), //订单金额
                'keyword4'=>$order['receiver_pcd'].$order['receiver_address'], //商品名称
                'keyword5'=>$order['receiver_name'], //支付金额
                'keyword6'=>"{$order['receiver_mobile']}", //支付方式
                'keyword7'=>'速冻物流', //支付时间
            ],
            'emphasis_keyword' => 'keyword4.DATA'
        ];
        $re = sendOrdertmp($d);
        if ($re !== true) {
            $d['error'] = $re;
            Log::init(Config::get('log_notify'));
            Log::record($d,'tmpmsg');
        }
    }


    /**
     * 待配送订单
     * @return [type] [description]
     */
    function send(){
    	$keywords = Request()->get('keywords');
        $sort = Request()->get('create_time')?Request()->get('create_time'):"create_time desc";
        $this->assign('sort',$sort);
    	$uid = $this->uid;
    	$Query = Db::field('*')->table('sdzx_shipping')->alias('s')
    	->join('sdzx_order o','s.order_id=o.order_id')
    	// ->where('s.shipping_status=0')
        ->order($sort.',s.shipping_status asc');

        if ($keywords) {
			$Query->where("s.delivery_name like '%{$keywords}%' or o.receiver_name like '%{$keywords}%' or o.receiver_mobile like '%{$keywords}%' ");
		}
    	$list = $Query->order('s.shipping_id asc')->where('o.order_status=40')->paginate('',false,['query'=>Request()->param()]);
    	return $this->fetch('send',['list'=>$list]);
    }

    /**
     * 已完成订单
     * @return [type] [description]
     */
    function finish(){
    	$keywords = Request()->get('keywords');
    	$uid = $this->uid;
    	$Query = Db::field('*')->table('sdzx_shipping')->alias('s')
    	->join('sdzx_order o','s.order_id=o.order_id')
    	->where('s.shipping_status=3');

        if ($keywords) {
			$Query->where("s.delivery_name like '%{$keywords}%' or o.user_name like '%{$keywords}%' ");
		}
    	$list = $Query->order('s.shipping_id asc')->select();
    	return $this->fetch('finish',['list'=>$list]);
    }

    /**
     * 商品列表
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function goods()
    {
    	$params = Request()->param();

    	$Query = Db::field('*')
    	->table('sdzx_shipping')->alias('s')
    	->join('sdzx_order o','s.order_id=o.order_id')
    	->join('sdzx_order_goods og','o.order_id=og.order_id');

    	if (isset($params['shipping_id'])) {
    		$Query->where("s.shipping_id={$params['shipping_id']}");
    	}

    	if (isset($params['keywords'])) {
			$Query->where("o.user_name like '%{$keywords}%' ");
		}

    	$list = $Query->select();
    	return $this->fetch('goods',['list'=>$list]);
    }

    /**
     * 网页打印 总单
     * @return [type] [description]
     */
    function webPrint(){
        $param = Request()->param();
        !$param['ids'] && $this->error('参数错误');

        $goods = Db::field('*')
    	->table('sdzx_shipping')->alias('s')
    	->join('sdzx_order o','s.order_id=o.order_id')
    	->join('sdzx_order_goods og','o.order_id=og.order_id')
    	->where(['shipping_id'=>['in',$param['ids']]])
        ->order('delivery_id asc')
    	->select();
        // 根据订单归类
        $order = [];$delivery = false;
        foreach ($goods as $k => $v) {
            if ( !isset( $order[$v['shipping_id']]['shipping_id']  ) ) {
                $order[$v['shipping_id']] = [
					'shipping_id'          => $v['shipping_id'],
					'shipping_create_time' => $v['shipping_create_time'],
					'delivery_name'        => $v['delivery_name'],
					'shipping_status'      => $v['shipping_status'],
					'shipping_create_name' => $v['shipping_create_name'],
					'order_no'             => $v['order_no'],
                ];
            }
            $order[$v['shipping_id']]['list'][] = $v;
            if ($delivery === false) {
                $delivery = $v['delivery_id'];
            }else{
                if ($delivery != $v['delivery_id']) {
                    $order[$v['shipping_id']]['break'] = true;
                }else{
                    $order[$v['shipping_id']]['break'] = false;
                }
            }
        }
        $data['list'] = $order;
        return $this->fetch('webprint',$data);
    }

    /**
     * 网页打印 分单
     * @return [type] [description]
     */
    function webPrintf(){
        $param = Request()->param();
        !$param['ids'] && $this->error('参数错误');

        $goods = Db::field('*')
        ->table('sdzx_shipping')->alias('s')
        ->join('sdzx_order o','s.order_id=o.order_id')
        ->join('sdzx_order_goods og','o.order_id=og.order_id')
        ->where(['shipping_id'=>['in',$param['ids']]])
        ->order('delivery_id asc')
        ->select();
        // 根据用户订单归类
        $order = [];$delivery = false;
        foreach ($goods as $k => $v) {
            unset($v['openid']);
            if ( !isset( $order[$v['order_id']]['order_id']  ) ) {
                $agent = Db::field('e.*')->table('sdzx_employee')->alias('e')
                ->join('sdzx_shop s','e.id=s.agent_id')
                ->where("s.user_id={$v['user_id']}")->find();
                // if (!$agent){
                //     $agent =  Db::field('e.*')->table('sdzx_employee')
                //         ->alias('e')->join('sdzx_employee_group_relation r','e.id=r.uid')
                //         ->join('sdzx_employee_group g','r.group_id=g.id')
                //         ->where("g.right_data=1 and g.code='GJ'")->find();
                // }
                $buy_user = Db::field('u.*,sp.shop_name')
                ->table('sdzx_user')->alias('u')
                ->join('sdzx_shop sp','u.shop_id=sp.shop_id','left')
                ->where(['id'=>$v['user_id']])->find();
                $delivery_list = Db::field('*')->table('sdzx_employee')->where(['id'=>$v['delivery_id']])->find();
                $order[$v['order_id']] = [
                    'order_id'         => $v['order_id'],
                    'receiver_name'    => $v['receiver_name'],
                    'receiver_mobile'  => $v['receiver_mobile'],
                    'receiver_pcd'     => $v['receiver_pcd'],
                    'receiver_address' => $v['receiver_address'],
                    'order_no'         => $v['order_no'],
                    'delivery_name'    => $v['delivery_name'],
                    'create_time'      => $v['create_time'],
                    'pay_time'         => $v['pay_time'],
                    'agent_name'       => $agent['name']?:'未分配',
                    'agent_phone'      => $agent['phone']?:Config::get('sites.company_phone'),
                    'u_phone'          => $buy_user['phone'],
                    'shop_name'        => $buy_user['shop_name'],
                    'goods_money'      => $v['goods_money'],
                    'order_money'      => $v['order_money'],
                    'pay_money'        => $v['pay_money'],
                    'shipping_money'   => $v['shipping_money'],
                    'pay_platform'     => $v['pay_platform'],
                    // 'delivery_name'    => $delivery_list['name'],
                    'delivery_phone'    => $delivery_list['phone']
                ];
            }

            $order[$v['order_id']]['list'][] = $v;
            $order[$v['order_id']]['totalnum'] = $order[$v['order_id']]['totalnum']+$v['num'];
        }
        $data['list'] = $order;
        $data['user'] = $this->user;
        return $this->fetch('',$data);
    }

    /**
     * 网页打印 分单
     * @return [type] [description]
     */
    function bPrint(){
        $param = Request()->param();
        !$param['ids'] && $this->error('参数错误');

        $goods = Db::field('*')
        ->table('sdzx_order')->alias('o')
        ->join('sdzx_order_goods og','o.order_id=og.order_id')
        ->where(['o.order_id'=>['in',$param['ids']]])
        ->select();
        // 根据用户订单归类
        $order = [];$delivery = false;
        foreach ($goods as $k => $v) {
            unset($v['openid']);
            if ( !isset( $order[$v['order_id']]['order_id']  ) ) {
                $agent = Db::field('e.*')->table('sdzx_employee')->alias('e')
                ->join('sdzx_shop s','e.id=s.agent_id')
                ->where("s.user_id={$v['user_id']}")->find();
                // if (!$agent){
                //     $agent =  Db::field('e.*')->table('sdzx_employee')
                //         ->alias('e')->join('sdzx_employee_group_relation r','e.id=r.uid')
                //         ->join('sdzx_employee_group g','r.group_id=g.id')
                //         ->where("g.right_data=1 and g.code='GJ'")->find();
                // }
                $buy_user = Db::field('u.*,sp.shop_name')
                ->table('sdzx_user')->alias('u')
                ->join('sdzx_shop sp','u.shop_id=sp.shop_id','left')
                ->where(['id'=>$v['user_id']])->find();
                // $delivery_list = Db::field('*')->table('sdzx_employee')->where(['id'=>$v['delivery_id']])->find();
                $order[$v['order_id']] = [
                    'order_id'         => $v['order_id'],
                    'receiver_name'    => $v['receiver_name'],
                    'receiver_mobile'  => $v['receiver_mobile'],
                    'receiver_pcd'     => $v['receiver_pcd'],
                    'receiver_address' => $v['receiver_address'],
                    'order_no'         => $v['order_no'],
                    'delivery_name'    => $v['delivery_name'],
                    'create_time'      => $v['create_time'],
                    'pay_time'         => $v['pay_time'],
                    'agent_name'       => $agent['name']?:'未分配',
                    'agent_phone'      => $agent['phone']?:Config::get('sites.company_phone'),
                    'u_phone'          => $buy_user['phone'],
                    'shop_name'        => $buy_user['shop_name'],
                    'goods_money'      => $v['goods_money'],
                    'order_money'      => $v['order_money'],
                    'pay_money'        => $v['pay_money'],
                    'shipping_money'   => $v['shipping_money'],
                    'pay_platform'     => $v['pay_platform'],
                    // 'delivery_name'    => $delivery_list['name'],
                    // 'delivery_phone'    => $delivery_list['phone']
                    'delivery_phone'    => ''
                ];
            }

            $order[$v['order_id']]['list'][] = $v;
            $order[$v['order_id']]['totalnum'] = $order[$v['order_id']]['totalnum']+$v['num'];
        }
        $data['list'] = $order;
        $data['user'] = $this->user;
        return $this->fetch('',$data);
    }

    /**
     * 配送完成操作
     * @return [type] [description]
     */
    public function pfinsh()
    {
        $param = Request()->param();
        !$param['ids'] && $this->error('参数错误');

        $shipping = Db::name('shipping')->where(['shipping_id'=>['in',$param['ids']]])->select();

        Db::startTrans();
        foreach ($shipping as $k => $v) {
            $order = Db::name('order')->where(['order_id'=>$v['order_id']])->find();
            
            $re_p = Db::name('shipping')->where(['shipping_id'=>$v['shipping_id']])->update(['shipping_status'=>1,'finish_time'=>date('Y-m-d H:i:s')]);
            if ($re_p === false) {
                Db::rollback(); $this->error('操作失败');
            }

            $up_o = [ 'shipping_status'=>1, 'finish_time'=>date('Y-m-d H:i:s')];
            if ($order['order_status'] == 30 || $order['order_status'] == 40) {
                $up_o['order_status'] = 100;
            }

            $re_o = Db::name('order')->where(['order_id'=>$v['order_id']])->update($up_o);
            if ($re_o === false) {
                Db::rollback(); $this->error('操作失败');
            }
            Db::name('order_action')->insert([
                'user_id'          => $order['user_id'],
                'order_id'         => $order['order_id'],
                'act_time'         => date('Y-m-d H:i:s'),
                'order_status'     => 100,
                'bop_order_status' => $order['order_status']
            ]);
        }
        Db::commit();
        $this->success('操作成功','refresh');
    }

    public function statistics()
    {
        $iw=Request()->param();

        $start_time=isset($iw['start_time'])?strtotime($iw['start_time']):'';
        $end_time=isset($iw['end_time'])?strtotime($iw['end_time']):'';

        if($end_time){
            $_end_time=getOneDay($end_time);
            // $_end_time=$_end_time['et'];
            if ($end_time==$_end_time['st']) {
                $end_time=$_end_time['et'];
            }
        }else{
            $end_time=getOneDay();
            $end_time=$end_time['et'];
        }

        if ($start_time) {
            // $start_time=getOneDay($start_time);
            // $start_time=$start_time['st'];
        }else{
            $start_time=getDayRegion($end_time,30);
            $start_time=$start_time['st'];
        }
        
        $iw['start_time']=date('Y-m-d H:i:s',$start_time);
        $iw['end_time']=date('Y-m-d H:i:s',$end_time);
        if ($iw['selt']!=='0') {
            $iw['selt']=$iw['selt']?:9;
        }
        $data['w']=$iw;

        $list = Db::field('e.id,e.name,eg.code,s.*,o.order_id,o.order_no,o.order_money')
        ->table('sdzx_employee')->alias('e')
        ->join('sdzx_employee_group_relation egr','e.id=egr.uid')
        ->join('sdzx_employee_group eg','egr.group_id=eg.id')
        ->join('sdzx_shipping s',"find_in_set(e.id,s.delivery_id) != 0 and s.shipping_create_time between '{$iw['start_time']}' and '{$iw['end_time']}'",'left')
        ->join('sdzx_order o','s.order_id=o.order_id','left')
        ->order('e.id asc')
        ->where("eg.code='PS'")
        ->select();
        

        $arr = [];
        foreach ($list as $k => $v) {
            if (!isset($arr[$v['id']]['id'])) {
                $arr[$v['id']]['id'] = $v['id'];
                $arr[$v['id']]['name'] = $v['name'];
                $arr[$v['id']]['time'] = 0;
                $arr[$v['id']]['timenum'] = 0;
                $arr[$v['id']]['totalnum'] = 0;
                $arr[$v['id']]['totalmoney'] = 0;
            }
            if ($v['order_id']) {
                $arr[$v['id']]['totalnum'] += 1;
                $arr[$v['id']]['totalmoney'] += $v['order_money'];
                if ($v['finish_time']) {
                    $arr[$v['id']]['time'] += (strtotime($v['finish_time'])-strtotime($v['shipping_create_time']))/60;
                    $arr[$v['id']]['timenum'] += 1;
                }
            }
            
            
        }

        $data['w']=$iw;
        $data['list']=$arr;
        return $this->fetch('',$data);
    }

    public function orderlist()
    {
        $param = request()->param();
        $list = Db::field('o.*,sp.shop_name')
        ->table('sdzx_order')->alias('o')
        ->join('sdzx_shipping s','o.order_id=s.order_id')
        ->join('sdzx_shop sp','o.user_id=sp.user_id','left')
        ->where("find_in_set({$param['id']},s.delivery_id) != 0 and s.shipping_create_time between '{$param['start_time']}' and '{$param['end_time']}'")
        ->select();
        $data['list']=$list;
        return $this->fetch('',$data);
    }
}